import time
start = time.time()
N = 51
V = [int("1" * i) if i > 0 else 0 for i in range(N + 1)]
base = [set() for i in range(N + 1)]
base[0].add(0)
vis = {0 : 0}
for i in range(1, 30):
for j in range(i):
for k in base[j]:
for v in [k + V[i - j], abs(k - V[i - j])]:
if v not in vis:
base[i].add(v)
vis[v] = i
s = input()
n = int(s)
ans = sum(((len(s) - i) + (len(s) - i - 1)) * int(s[i]) for i in range(len(s)))
def solve(x, steps):
global ans
x = abs(x)
if time.time() - start > 2.9:
print(ans)
exit(0)
if x in vis:
ans = min(ans, steps + vis[x])
return
for i in range(50, 1, -1):
if V[i] <= x:
if steps + i >= ans:
return
y, stp = x, steps
while y >= V[i]:
y -= V[i]
stp += i
p1 = (y, stp)
y, stp = abs(x - V[i + 1]), steps + i + 1
cnt = 0
while y >= V[i]:
y -= V[i]
stp += i
cnt += 1
if cnt > 4:
solve(*p1)
return
p2 = (y, stp)
if p1[1] > p2[1]:
p1, p2 = p2, p1
solve(*p1)
solve(*p2)
return
solve(n, 0)
print(ans)
exit(0)
281A - Word Capitalization | 1646A - Square Counting |
266A - Stones on the Table | 61A - Ultra-Fast Mathematician |
148A - Insomnia cure | 1650A - Deletions of Two Adjacent Letters |
1512A - Spy Detected | 282A - Bit++ |
69A - Young Physicist | 1651A - Playoff |
734A - Anton and Danik | 1300B - Assigning to Classes |
1647A - Madoka and Math Dad | 710A - King Moves |
1131A - Sea Battle | 118A - String Task |
236A - Boy or Girl | 271A - Beautiful Year |
520B - Two Buttons | 231A - Team |
479C - Exams | 1030A - In Search of an Easy Problem |
158A - Next Round | 71A - Way Too Long Words |
160A - Twins | 1A - Theatre Square |
1614B - Divan and a New Project | 791A - Bear and Big Brother |
1452A - Robot Program | 344A - Magnets |